class SyntheticEvent {
  constructor(e) {
    this.nativeEvent = e;
  }
  stopPropagation() {
    this._stopPropagation = true;
    if (this.nativeEvent.stopPropagation) {
      this.nativeEvent.stopPropagation();
    }
  }
}

const triggerEventFlow = (paths, type, se) => {
  for (let i = paths.length; i--; ) {
    const pathNode = paths[i];
    const callback = pathNode[type];
    if (callback) {
      callback.call(null, se);
    }
    if (se._stopPropagation) {
      break;
    }
  }
};

const dispatchEvent = (e, type) => {
  // 包装合成事件
  const se = new SyntheticEvent(e);
  console.log('se', se)
  const ele = e.target;
  let fiber;
  for (let prop in ele) {
    if (prop.toLowerCase().includes("fiber")) {
      fiber = ele[prop];
    }
  }
  console.log('fiber', fiber, type, 'type');
  // 第三步：收集路径中“该事件的所有回调函数”
  const paths = collectPaths(type, fiber);
  console.log([...paths], 'paths')
  // 第四步：捕获阶段的实现
  triggerEventFlow(paths, type + "CAPTURE", se);
  // 第五步：冒泡阶段的实现
  if (!se._stopPropagation) {
    triggerEventFlow(paths.reverse(), type, se);
  }
};

const collectPaths = (type, begin) => {
  const paths = [];
  console.log('begin', begin, type)
  // 不是根FiberNode的话，就一直向上遍历
  while (begin.tag !== 3) {
    const { memoizedProps, tag } = begin;
    // 5代表DOM节点对应FiberNode
    if (tag === 5) {
      const eventName = ("on" + type).toUpperCase();
      console.log('eventName', eventName)
      // 如果包含对应事件回调，保存在paths中
      if (memoizedProps && Object.keys(memoizedProps).includes(eventName)) {
        const pathNode = {};
        pathNode[type.toUpperCase()] = memoizedProps[eventName];
        paths.push(pathNode);
      }
    }
    begin = begin.return;
  }
  return paths;
};

export const addEvent = (container, type) => {
  container.addEventListener(type, (e) => {
    console.log(e, 'e');
    dispatchEvent(e, type.toUpperCase(), container);
  });
};
